package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.query.PageResult;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public void saveOrUpdate(Employee entity) {
        if (entity.getId() == null) {
            employeeMapper.insert(entity);
            List<Role> roles = entity.getRoles();
            for (Role role : roles) {
                employeeMapper.insertRoleRelation(entity.getId(),role.getId());
            }
        }else {
            employeeMapper.updateByPrimaryKey(entity);
            employeeMapper.deleteRoleRelation(entity.getId());
            List<Role> roles = entity.getRoles();
            for (Role role : roles) {
                employeeMapper.insertRoleRelation(entity.getId(),role.getId());
            }
        }
    }

    @Override
    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> list() {
        return employeeMapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject qo) {
        //1.查询记录总数
        int count =  employeeMapper.query4Count(qo);
        if (count == 0) {
            return new PageResult(0,Collections.EMPTY_LIST);
        }
        List<Employee> list = employeeMapper.query4List(qo);
        //2.查询分页数据

        return new PageResult(count,list);
    }

    @Override
    public void changeState(Long empId) {
        employeeMapper.changeState(empId);
    }

    @Override
    public Employee getByUsername(String username) {
        return employeeMapper.getUsername(username);
    }

    @Override
    public List<Long> selectRoleByEmpId(Long empId) {
        return employeeMapper.selectRoleByEmpId(empId);
    }
}
